<template>
  <!-- 移除 chat-container 外壳，直接保留内部元素 -->
  <div class="chat-header">
    <p>历史对话</p>
    <div class="header-controls">
      <el-button
          type="text"
          size="small"
          @click="showClearDialog = true"
          :disabled="messages.length === 0"
      >
        <el-icon :size="16" name="delete"></el-icon>
        清空对话
      </el-button>
    </div>
  </div>

  <div class="message-list" ref="messageList">
    <!-- 欢迎消息 - 仅在对话为空时显示 -->
    <div class="welcome-message" v-if="messages.length === 0 && !deepseekLoading">
      <div class="welcome-icon">
        <el-icon :size="48" name="chat-round"></el-icon>
      </div>
      <h3>欢迎使用智能对话助手</h3>
      <p>我可以帮助你解答问题、提供信息和建议</p>
      <p>输入你的问题，按Enter发送消息</p>
    </div>

    <div
        class="message-item"
        v-for="msg in messages"
        :key="msg.id"
        :class="{ 'ai-message': msg.isAI, 'user-message': !msg.isAI }"
    >
      <div class="avatar" v-if="msg.isAI">
        <el-icon class="icon" name="chat-round"></el-icon>
      </div>
      <div class="message-bubble">
        <div class="content" v-if="msg.isAI" v-html="msg.html"></div>
        <div class="content" v-else>{{ msg.text }}</div>
        <div class="time">{{ formatTime(msg.timestamp) }}</div>
      </div>
      <div class="avatar" v-if="!msg.isAI">
        <el-icon class="icon" name="user"></el-icon>
      </div>
    </div>

    <div class="loading-indicator" v-if="deepseekLoading">
      <el-icon :size="20" class="loading-icon" name="loading"></el-icon>
      <span class="loading-text">AI正在思考...</span>
    </div>
  </div>

  <div class="input-area">
    <el-input
        v-model="message"
        placeholder="输入消息，按Enter发送，Shift+Enter换行..."
        :disabled="deepseekLoading"
        @keydown.enter.exact="sendMessage"
        @keydown.enter.shift="handleShiftEnter"
        type="textarea"
        :rows="3"
        clearable
        class="message-input"
    />
    <div class="button-group">
      <el-button
          type="primary"
          @click="sendMessage"
          :loading="deepseekLoading"
          class="send-btn"
          :disabled="!message.trim() || deepseekLoading"
      >
        <el-icon :size="18" name="send"></el-icon>
        发送
      </el-button>
      <el-button
          type="default"
          @click="updateConversation"
          :loading="deepseekLoading"
          :disabled="messages.length === 0 || deepseekLoading"
      >
        <el-icon :size="18" name="refresh"></el-icon>
        更新对话
      </el-button>
    </div>
  </div>

  <!-- 清空对话确认框 -->
  <el-dialog
      v-model="showClearDialog"
      title="确认清空"
      width="300px"
      :show-close="false"
  >
    <p>确定要清空当前对话记录吗？</p>
    <template #footer>
      <el-button @click="showClearDialog = false">取消</el-button>
      <el-button type="primary" @click="clearConversation">确认清空</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 脚本部分保持不变
import { reactive, ref, watch, nextTick, onMounted } from 'vue'
import { useDeepseekService } from '@/api/Table/deepseekApi'
import { v4 as uuidv4 } from 'uuid'
import { marked } from 'marked';
import { sqlStore } from '@/stroe/sql/sql.js'
import {apiKeyStore} from "@/stroe/sql/ApiKey.js";

interface Message {
  id: string
  text: string
  html: string
  isAI: boolean
  timestamp: Date
}

// 生成新的对话ID
const generateConvId = () => {
  return Math.random().toString(36).substring(2, 10);
}

const convId = ref(generateConvId())
const { deepseek, loading: deepseekLoading } = useDeepseekService()

const message = ref('')
const messageList = ref<HTMLElement | null>(null)
const messages = reactive<Message[]>([])
const showClearDialog = ref(false)

const params = reactive({
  convId: convId.value,
  apiKey: apiKeyStore.apiKey,
  query: "",
  model: apiKeyStore.model,
})

// 格式化时间显示
const formatTime = (date: Date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

// 处理Shift+Enter换行
const handleShiftEnter = () => {
  message.value += '\n'
}

// 发送消息
const sendMessage = async () => {
  const userInput = message.value.trim()
  if (!userInput || deepseekLoading.value) return
  // 添加用户消息
  const userMsg: Message = {
    id: uuidv4(),
    text: userInput,
    html: '',
    isAI: false,
    timestamp: new Date()
  }
  messages.push(userMsg)
  message.value = ""

  try {
    // 构建查询参数，包含SQL信息
    let query = ""
    if (sqlStore.sql2IsSend) query =sqlStore.sql2+"。"+ userInput+"。"
    if (sqlStore.sql1IsSend) query = query+"请你参考一下sql表回答我的问题，" +
        "如果我问的是有关生成增删改查等sql语句"+ sqlStore.sql1

    params.convId = convId.value
    params.query = query

    // 调用AI接口
    const res = await deepseek(params)
    const aiReply = (res as any).data?.data || "收到消息，但未获取到具体内容"

    // 添加AI回复
    messages.push({
      id: uuidv4(),
      text: aiReply,
      html: marked.parse(aiReply),
      isAI: true,
      timestamp: new Date()
    })
  } catch (err: any) {
    let errorMsg = "发送失败，请稍后重试"
    if (err.message.includes('Network Error')) {
      errorMsg = "网络连接失败，请检查网络"
    } else if (err.response?.status === 401) {
      errorMsg = "API密钥无效，请检查配置"
    }

    messages.push({
      id: uuidv4(),
      text: errorMsg,
      html: errorMsg,
      isAI: true,
      timestamp: new Date()
    })
  }
}

// 更新对话 - 保留用户问题，重新获取AI回复
const updateConversation = async () => {
  if (messages.length === 0 || deepseekLoading.value) return

  // 找到最后一条用户消息
  const lastUserMessage = messages.slice().reverse().find(msg => !msg.isAI)
  if (!lastUserMessage) return

  // 移除最后一条AI回复（如果存在）
  const lastAiMessageIndex = messages.findLastIndex(msg => msg.isAI)
  if (lastAiMessageIndex > -1) {
    messages.splice(lastAiMessageIndex, 1)
  }

  try {
    // 构建查询参数，包含SQL信息
    let query = lastUserMessage.text
    if (sqlStore.sql1IsSend) query += sqlStore.sql1
    if (sqlStore.sql2IsSend) query += sqlStore.sql2

    params.convId = convId.value
    params.query = query

    // 调用AI接口重新获取回复
    const res = await deepseek(params)
    const aiReply = (res as any).data?.data || "收到消息，但未获取到具体内容"

    // 添加新的AI回复
    messages.push({
      id: uuidv4(),
      text: aiReply,
      html: marked.parse(aiReply),
      isAI: true,
      timestamp: new Date()
    })
  } catch (err: any) {
    let errorMsg = "更新失败，请稍后重试"
    if (err.message.includes('Network Error')) {
      errorMsg = "网络连接失败，请检查网络"
    } else if (err.response?.status === 401) {
      errorMsg = "API密钥无效，请检查配置"
    }

    messages.push({
      id: uuidv4(),
      text: errorMsg,
      html: errorMsg,
      isAI: true,
      timestamp: new Date()
    })
  }
}

// 清空对话
const clearConversation = () => {
  messages.length = 0
  convId.value = generateConvId() // 生成新的对话ID
  showClearDialog.value = false
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(messages, scrollToBottom, { deep: true })
onMounted(scrollToBottom)

// 限制消息数量，防止内存占用过大
watch(messages, () => {
  if (messages.length > 100) {
    messages.splice(0, messages.length - 100)
  }
})
</script>

<style scoped>
/* 移除原 chat-container 样式，调整整体布局样式到父级和内部元素 */
* {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  /* 新增：确保整体容器垂直布局 */
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.chat-header {
  padding: 14px 30px;
  border-bottom: 1px solid #f0f2f5;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  color: #1d2129;
  font-weight: 600;
}

.header-controls {
  display: flex;
  gap: 10px;
}

/* 消息列表区域 - 关键调整：占满剩余空间 */
.message-list {
  flex: 1; /* 核心：占满父容器剩余高度 */
  overflow-y: auto;
  padding: 20px;
  background-color: #f7f8fa;
  min-height: 0;
  scroll-behavior: smooth;
}

/* 欢迎消息样式 */
.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: #86909c;
  max-width: 500px;
  margin: 0 auto;
}

.welcome-icon {
  margin-bottom: 20px;
  color: #409eff;
  opacity: 0.8;
}

.welcome-message h3 {
  margin: 0 0 10px 0;
  color: #1d2129;
  font-size: 18px;
}

.welcome-message p {
  margin: 6px 0;
  font-size: 14px;
  line-height: 1.6;
}

/* 消息项样式 */
.message-item {
  display: flex;
  margin-bottom: 18px;
  max-width: 80%;
  animation: fadeIn 0.3s ease;
  align-items: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
  align-self: flex-end;
}

/* 头像样式 */
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
}

.avatar:hover {
  transform: scale(1.05);
}

.ai-message .avatar {
  background-color: #f0f2f5;
  color: #409eff;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #409eff;
  color: white;
}

.icon {
  transition: transform 0.2s ease;
}

.avatar:hover .icon {
  transform: scale(1.1);
}

/* 消息气泡样式 */
.message-bubble {
  position: relative;
  padding: 12px 16px;
  border-radius: 14px;
  word-break: break-word;
  line-height: 1.6;
  max-width: calc(100% - 46px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.message-bubble:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ai-message .message-bubble {
  background-color: white;
  border: 1px solid #f0f2f5;
  border-top-left-radius: 4px;
}

.user-message .message-bubble {
  background-color: #409eff;
  color: white;
  border-top-right-radius: 4px;
}

/* 时间样式 */
.time {
  font-size: 12px;
  margin-top: 4px;
  opacity: 0.7;
  text-align: right;
  transition: opacity 0.2s ease;
}

.message-bubble:hover .time {
  opacity: 1;
}

/* 输入区域样式 */
.input-area {
  display: flex;
  gap: 12px;
  padding: 16px 30px;
  border-top: 1px solid #f0f2f5;
  background-color: #fff;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.03);
}

.message-input {
  flex: 1;
  transition: all 0.2s ease;
}

.message-input:hover,
.message-input:focus-within {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.button-group {
  display: flex;
  gap: 8px;
}

.send-btn {
  flex-shrink: 0;
  align-self: flex-end;
}

/* 加载指示器样式 */
.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  color: #606266;
  animation: pulse 1.5s infinite;
}

.loading-text {
  margin-left: 8px;
  font-size: 14px;
}

/* 滚动条样式优化 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: transparent;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.message-list::-webkit-scrollbar-thumb:active {
  background: #888;
}

/* Markdown样式支持 */
.ai-message .content {
  font-size: 14px;
  line-height: 1.6;
}

.ai-message .content h1,
.ai-message .content h2,
.ai-message .content h3,
.ai-message .content h4,
.ai-message .content h5,
.ai-message .content h6 {
  margin: 12px 0 8px;
  font-weight: 600;
  color: #333;
}

.ai-message .content h1 {
  font-size: 1.5em;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.ai-message .content h2 {
  font-size: 1.3em;
  border-bottom: 1px solid #f5f5f5;
  padding-bottom: 6px;
}

.ai-message .content h3 {
  font-size: 1.1em;
}

.ai-message .content p {
  margin: 8px 0;
}

.ai-message .content ul,
.ai-message .content ol {
  margin: 8px 0;
  padding-left: 24px;
}

.ai-message .content ul {
  list-style-type: disc;
}

.ai-message .content ol {
  list-style-type: decimal;
}

.ai-message .content pre {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  margin: 10px 0;
}

.ai-message .content code {
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}

.ai-message .content a {
  color: #409eff;
  text-decoration: none;
}

.ai-message .content a:hover {
  text-decoration: underline;
}

.ai-message .content blockquote {
  border-left: 3px solid #409eff;
  padding-left: 10px;
  margin: 10px 0;
  color: #666;
  font-style: italic;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-item {
    max-width: 90%;
  }

  .chat-header {
    padding: 12px 16px;
  }

  .input-area {
    padding: 12px 16px;
    gap: 8px;
  }

  .button-group {
    flex-direction: column;
  }

  .message-list {
    padding: 12px;
  }
}
</style>